import re
import json
import logging

from django.contrib.auth.mixins import LoginRequiredMixin

logger=logging.getLogger('django')

from django.contrib.auth import login,logout, authenticate
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views import View
from django_redis import get_redis_connection

from meiduo_mall.utils.view import login_required
from users.models import User, Address


#用户名重复检查功能
class UsernameCountview(View):
    """判断用户是否重复注册"""

    def get(self, request, username):
        """判断用户名是否重复"""
        #1.查询此username在数据库中个数
        try:
            count = User.objects.filter(username=username).conut()
        except Exception as e:
            return JsonResponse({'code':400,'errmsg':'访问数据库失败'})

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'count': count})

#手机号重复检查功能
class MobileCountview(View):
    """判断手机号是否重复"""
    def get(self, request, mobile):
        """判断手机号是否重复"""
        #1.查询此手机号在数据库中个数
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return JsonResponse({'code':400,'errmsg':'访问数据哭失败'})
        #返回响应
        return JsonResponse({'code':0,'errmsg':'ok','conut':count})

#注册功能
class RegisterView(View):
    def post(self,request):
        # 1.接收参数
        dict = json.loads(request.body.decode())
        username = dict.get('username')
        password = dict.get('password')
        password2 = dict.get('password2')
        mobile = dict.get('mobile')
        sms_code = dict.get('sms_code')
        allow = dict.get('allow')


        # 2.校验参数
        #1.必要参数检验
        if not all([username,password,password2,mobile,sms_code,allow]):
            return JsonResponse({'code':400,
                                'errmsg':'缺少参数'})
        # 2.username检验
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({'code': 400,
                                'errmsg': 'username格式有误'})

        # 3.password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'code': 400,
                                'errmsg': 'password格式有误'})

        # 4.password2 和 password
        if password != password2:
            return JsonResponse({'code': 400,
                                'errmsg': '两次输入不对'})
        # 5.mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                'errmsg': 'mobile格式有误'})
        # 6.allow检验
        if allow != True:
            return JsonResponse({'code': 400,
                                'errmsg': 'allow格式有误'})
        # 7.sms_code检验
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_code%s'%mobile).decode()
        if sms_code != sms_code_server:
            return JsonResponse({'code':400,
                                 'errmsg':'短信验证码错误'})

        # 3.保存参数
        try:
            user=User.objects.create_user(username=username,
                                password=password,
                                mobile=mobile)
        except Exception as e:
            print(1)
            return JsonResponse({'code':400,
                                'errmsg':'注册失败'})

        #保持登录
        login(request, user)
        # 4.构建响应(设置cookie)
        response = JsonResponse({'code':0,
                             'errmsg':'注册成功'})

        response.set_cookie('username',user.username,max_age = 3600*24*14)

        return response
#登录功能
class LoginView(View):
    def post(self,request):
        login_data=json.loads(request.body.decode())
        username=login_data.get('username')
        password=login_data.get('password')
        remembered=login_data.get('remembered')

        if not all([username,password]):
            return JsonResponse({
                'code':400,
                'errmsg':'参数不齐'
            })

        user =authenticate(username=username,
                           password=password)

        if user is None:
            return JsonResponse({'code':400,
                                 'errmsg':'用户名或者密码错误'})

        login(request,user)

        if remembered != True:
            #如果没有记住: 关闭立刻失效
            request.session.set_expiry(0)
        else:
            #如果记住:  设置为两周有效
            request.session.set_expiry(None)

        response = JsonResponse({'code': 0,
                                 'errmsg': '注册成功'})

        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        return response

#退出功能
class LogoutView(View):
    def delete(self,request):

        # 清理 session
        logout(request)

        # 创建 response 对象.
        response = JsonResponse({'code':0,
                                 'errmsg':'ok'})

        # 调用对象的 delete_cookie 方法, 清除cookie
        response.delete_cookie('username')

        # 返回响应
        return response

#用户中心
class UserInfoView(View):
    @method_decorator(login_required)
    def get(self,request):
        user = request.user

        return JsonResponse({
            'code':0,
            'errmsg':"ok",
            'info_data':{
                'username':user.username,
                'mobile':user.mobile,
                'email':user.email,
                'email_active':user.email_active
            }

        })

#添加邮箱功能
class Emailview(View):
    def put(self,request):
        email_dict=json.loads(request.body.decode())
        email=email_dict.get('email')
        if not email:
            return JsonResponse({'code':400,'errmsg':'请填写邮箱'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数email有误'})
        try:
            request.user.email=email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400,
                                 'errmsg': '添加邮箱失败'})
         # 变换 email 的格式: 从 '123456@qq.com' 变为: '<123456@qq.com>'
        email = '<' + email + '>'
        # 从 celery_tasks 中导入:
        from celery_tasks.email.tasks import send_verify_email
        # 调用发送的函数:
        verify_url = request.user.generate_verify_email_url()
        send_verify_email.delay(email, verify_url)

        return JsonResponse({'code': 0,
                            'errmsg': 'ok'})

#验证邮箱
class VerifyEmailView(View):
    def put(self,request):
        token =request.GET.get('token')
        if not token:
            return JsonResponse({'code':400,
                                 'errmsg':'缺少参数'})
        user = User.check_verify_email_token(token)
        if not user:
            return JsonResponse({'code':400,
                                 'errmsg':'无效的token'})
        try:
            user.email_active = True
            User.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,
                                 'errmsg':'激活邮件失败'})
        return JsonResponse({'code':0,
                             'errmsg':'ok'})

#新增地址
class CreateAddressView(View):
    def post(self,request):
        #获取地址个数：
        try:
            count = Address.objects.filter(user=request.user,
                                           is_deleted=False).count()
        except Exception as e:
            return JsonResponse({'code':400,
                                 'errmsg':'获取地址数据出错'})
        # 判断是否超过地址上限：最多20个
        if count >=20:
            return JsonResponse({'code':400,
                                 'errmsg':'超过地址数量上限'})
        #接受参数
        json_dict=json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email =json_dict.get('email')

        #校验参数
        if not all([receiver,province_id,city_id,district_id,place,mobile]):
            return JsonResponse({'code':400,
                                 'errmsg':'缺少必要参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})

        #保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )

            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()

        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,
                                 'errmsg':'新增地址失败'})

        address_dict ={
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return JsonResponse({'code': 0,
                             'errmsg': '新增地址成功',
                             'address': address_dict})
#展示用户收货地址
class AddressView(View):

    def get(self,request):
        # 获取所有的地址:
        addresses =Address.objects.filter(user=request.user,
                 is_deleted=False)

        # 创建空的列表
        address_dict_list = []
        for address in addresses:
            address_dict ={
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }
            # 将默认地址移动到最前面
            default_address = request.user.default_address
            if default_address.id == address.id:
                address_dict_list.insert(0,address_dict)
            else:
                address_dict_list.append(address_dict)

        default_id = request.user.default_address_id

        return JsonResponse({'code':0,
                             'errmsg':'ok',
                             'addresses':address_dict_list,
                             'default_address_id':default_id})

#修改和删除地址
class UpdateDestroyAddressView(View):
    def put(self,request,address_id):
        """修改地址"""

        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        #校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})


        #选中传入的地址并更改
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,
                                 'errmsg':'更新地址失败'})

        #构建响应数据
        address = Address.objects.get(id=address_id)
        address_dict ={
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({
            'code':0,
            'errmsg':'更新地址成功',
            'address':address_dict
        })


    def delete(self,request,address_id):
        """删除地址"""
        try:
            address = Address.objects.get(id=address_id)

            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,
                                 'errmsg':'删除地址失败'})
        return JsonResponse({'code':0,
                             'errmsg':'删除地址成功'})

#设置默认地址
class DefaultAddressView(View):
    def put(self,request,address_id):
        try:
            address=Address.objects.get(id=address_id)

            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400,
                                 'errmsg': '设置默认地址失败'})

        return JsonResponse({'code': 0,
                             'errmsg': '设置默认地址成功'})


#设置地址标题
class UpdateTitleAddressView(View):
    def put(self,request,address_id):
        json_dict = json.loads(request.body.decode())
        title =json_dict.get('title')
        try:
            address= Address.objects.get(id=address_id)

            address.title =title
            address.save()

        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,
                                 'errmsg':'设置地址标题失败'})

        return JsonResponse({'code':0,
                             'errmsg':'设置地址标题成功'})


#修改密码
class ChangePasswordView(LoginRequiredMixin,View):
    def put(self,request):
        password_data = json.loads(request.body.decode())
        old_password = password_data.get('ola_password')
        new_password = password_data.get('new_password')
        new_password2 = password_data.get('new_password2')

        if not all([old_password,new_password,new_password2]):
            return JsonResponse({'code':400,
                                 'errmsg':'缺少必要参数'})

        result = request.user.check_password(old_password)
        if not result:
            return JsonResponse({'code': 400,
                                 'errmsg': '原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({'code': 400,
                                 'errmsg': '密码最少8位,最长20位'})

        if new_password != new_password2:
            return JsonResponse({'code': 400,
                                 'errmsg': '两次输入密码不一致'})

        #修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400,
                                 'errmsg': '修改密码失败'})
        # 清理状态保持信息
        logout(request)
        response =JsonResponse({'code':0,
                                'errmsg':'ok'})
        response.delete_cookie('username')

        return response